/***************************************************************************
 *   Copyright (C) 2010 by Oleg Goncharov  *
 *   $EMAIL$                           *                          
 *                                                                         *
 *   This file is part of ChessVision.                                     *
 *                                                                         *
 *   ChessVision is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <stdlib.h>
#include <opencv/highgui.h>
#include <iostream>

#include "../error/cerror.h"
#include "cimagedvgrab.h"

CImageDvGrab::CImageDvGrab(const char * options) {
	command = "dvgrab --format jpeg --duration 42ms ";
	if (options) command += options;
	command += " /tmp/frame 1>/dev/null 2>/dev/null";
}


IplImage * CImageDvGrab::GrabFrame() {
	Clear();
	int ret = system(command.c_str());
	if (ret == -1) throw Errors::CStdError();
	if (ret != 0) throw Errors::CError("CImageDvGrab: dvgrab error.");
	
	IplImage * tmp = cvLoadImage("/tmp/frame001-00000001.jpg");
	if (! tmp) throw Errors::CError("CImageDvGrab: Unable open frame image file.");
	
	//TODO There is something wrong
	CvSize size = cvGetSize(tmp);
	int height = size.height;
	size.height = int(0.758681*size.height);
	size.width = 640;
	CvMat submat;
	CvMat * subimg = cvGetSubRect(tmp, &submat, cvRect(40, int(0.111111f*height), size.width, size.height));
	size.height = int(0.911227*size.height);
	img = cvCreateImage(size, IPL_DEPTH_8U, 3);
	cvResize(subimg, img);
	cvSmooth(img, img, CV_GAUSSIAN, 3, 3);
	cvFlip(img);
	cvReleaseImage(&tmp);
	
	return img;
}


